package com.zbec.mdrs.license;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.MaskFormatter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zbec.mdrs.license.security.Crypto;
import com.zbec.mdrs.license.security.MD5Utils;
import com.zbec.mdrs.util.DateUtils;
import com.zbec.mdrs.util.SpringUtilities;

public class LicenseGenerator extends JPanel implements ActionListener,
		FocusListener {
	protected Logger logger = LoggerFactory.getLogger(LicenseGenerator.class);
	private static final long serialVersionUID = -3658965261367229897L;
	private JTextField expireInDays, key, startDate;
	private JFileChooser fDialog;
	private JLabel err_info = new JLabel();

	private List<JComponent> components;

	final static int GAP = 10;

	public static final String LICENSE_FILE_NAME = "client.license";

	public LicenseGenerator() {
		setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		add(err_info);
		add(createEntryFields());
		add(createButtons());
		initComponents();
	}

	private void initComponents() {
		components = new ArrayList<JComponent>();
		components.add(expireInDays);
		components.add(key);
		components.add(startDate);
		// components.add(filePath);

		if (err_info != null) {
			err_info.setVisible(false);
		}

	}

	protected JComponent createEntryFields() {
		JPanel panel = new JPanel(new SpringLayout());

		String[] labelStrings = { "过期天数 : ", "授权开始日期(yyyyMMdd) : ", "机密密钥 : " };

		JLabel[] labels = new JLabel[labelStrings.length];
		JComponent[] fields = new JComponent[labelStrings.length];
		int fieldNum = 0;

		// 创建所有组件
		// expireInDays = new JFormattedTextField(createFormatter("#####"));
		expireInDays = new JTextField();
		expireInDays.setColumns(15);
		fields[fieldNum++] = expireInDays;

		startDate = new JTextField();
		startDate.setColumns(10);
		fields[fieldNum++] = startDate;

		key = new JTextField();
		key.setColumns(20);
		fields[fieldNum++] = key;

		setDefaultValue(expireInDays, "90");
		setDefaultValue(startDate, DateUtils.parseDate(new Date(), "yyyyMMdd"));
		/*setDefaultValue(key, MD5Utils.encodePassword(PropertyUtil.getInstance().getProperty("client.identity")));*/

		for (int i = 0; i < labelStrings.length; i++) {
			labels[i] = new JLabel(labelStrings[i], JLabel.TRAILING);
			labels[i].setLabelFor(fields[i]);
			panel.add(labels[i]);
			panel.add(fields[i]);

			// Add listeners to each field.
			@SuppressWarnings("unused")
			JTextField tf = null;
			if (fields[i] instanceof JSpinner) {
				tf = getTextField((JSpinner) fields[i]);
			} else {
				tf = (JTextField) fields[i];
			}
		}
		SpringUtilities.makeCompactGrid(panel, labelStrings.length, 2, GAP,
				GAP, // init x,y
				GAP, GAP / 2);// xpad, ypad

		return panel;
	}

	protected JComponent createButtons() {

		JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		// panel.add(new JSeparator(JSeparator.HORIZONTAL));

		JButton button = new JButton("保存");
		button.addActionListener(this);
		button.setActionCommand("save");
		panel.add(button);

		button = new JButton("清空");
		button.addActionListener(this);
		button.setActionCommand("clear");
		panel.add(button);

		button = new JButton("退出");
		button.addActionListener(this);
		button.setActionCommand("exit");
		panel.add(button);

		/*
		 * button = new JButton("启动tomcat"); button.addActionListener(this);
		 * button.setActionCommand("bat"); panel.add(button);
		 */
		panel.setBorder(BorderFactory.createEmptyBorder(0, 0, GAP - 5, GAP - 5));
		return panel;
	}

	// A convenience method for creating a MaskFormatter.
	protected MaskFormatter createFormatter(String s) {
		MaskFormatter formatter = null;
		try {
			formatter = new MaskFormatter(s);
		} catch (java.text.ParseException exc) {
			System.err.println("formatter is bad: " + exc.getMessage());
			System.exit(-1);
		}
		return formatter;
	}

	public JFormattedTextField getTextField(JSpinner spinner) {
		JComponent editor = spinner.getEditor();
		if (editor instanceof JSpinner.DefaultEditor) {
			return ((JSpinner.DefaultEditor) editor).getTextField();
		} else {
			System.err.println("Unexpected editor type: "
					+ spinner.getEditor().getClass()
					+ " isn't a descendant of DefaultEditor");
			return null;
		}
	}

	private static void createAndShowGUI() {
		// 创建窗口
		JFrame frame = new JFrame("授权文件工具");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLocation(350, 100);
		// Add contents to the window.
		frame.add(new LicenseGenerator());

		// 显示窗口
		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) {
		UIManager.put("swing.boldMetal", Boolean.FALSE);
		createAndShowGUI();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if ("clear".equals(e.getActionCommand())) {
			// 清空所有的输入框
			for (int i = 0; i < components.size(); i++) {
				JComponent component = components.get(i);
				if (component instanceof JFormattedTextField) {
					((JFormattedTextField) component).setValue(null);
				} else if (component instanceof JTextField) {
					if (((JTextField) component).isEnabled()) {
						((JTextField) component).setText("");
					}
				}
			}
			// TODO 出错提示框处理

		} else if ("exit".equals(e.getActionCommand())) {
			// TODO 处理退出
			System.exit(0);
		} else if ("save".equals(e.getActionCommand())) {
			// 测试保存方法是否进入
			if (logger.isDebugEnabled()) {
				logger.debug("test save method---------");
			}

			if (!checkNumber(expireInDays.getText())) {
				showErrMsg(expireInDays, "输入正确的授权有效天数");
				return;
			}

			if (isNullOrEmpty(startDate.getText())) {
				showErrMsg(startDate, "输入开始日期(格式: yyyyMMdd)");
				return;
			}

			/*setDefaultValue(key, MD5Utils.encodePassword("centerbank"));*/

			fDialog = new JFileChooser();
			FileNameExtensionFilter filter = new FileNameExtensionFilter(
					"License File", "license");
			fDialog.setFileFilter(filter);
			fDialog.setCurrentDirectory(new File("."));
			fDialog.setSelectedFile(new File(LICENSE_FILE_NAME));
			int returnVal = fDialog.showDialog(this, "保存文件");
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				generateLincense();
			}

		} else if ("bat".equals(e.getActionCommand())) {
			if (logger.isDebugEnabled()) {
				logger.debug("test execute .bat");
			}
			// String cmd = "cmd.exe /C start \"" +
			// getClass().getResource("/").getPath()
			// + View.OO_server_fileName + "\"";

			String filePath = getClass().getResource("/").getPath();
			int index = filePath.lastIndexOf("webapps");
			// logger.debug(filePath.substring(0, index));
			String cmd = "cmd.exe /C start " + filePath.substring(0, index)
					+ "bin/startup.bat";
			// String cmd = "cmd /C start " +
			// "D:/tomcat_all/tomcat_6.0.18/webapps/USST/WEB-INF/classes/soffice.bat";

			try {
				Process ps = Runtime.getRuntime().exec(cmd);
				if (logger.isDebugEnabled()) {
					logger.debug(ps.getInputStream().toString());
				}
			} catch (IOException ioe) {
				logger.error(ioe.getMessage());
			}
		}
	}

	private void generateLincense() {
		StringBuffer content = new StringBuffer("");
		content.append("license.expireInDays=")
				.append(this.expireInDays.getText()).append("\n");
		content.append("license.startDate=").append(this.startDate.getText())
				.append("\n");
		String license = Crypto.encrypt(content.toString(), MD5Utils.encodePassword(this.key.getText()));

		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(this.fDialog.getSelectedFile()
					.getAbsolutePath());
			fos.write(license.getBytes());
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unused")
	private boolean checkIP(String text) {
		Pattern p = Pattern
				.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
		Matcher matcher = p.matcher(text);
		return matcher.matches();
	}

	private boolean checkNumber(String text) {
		Pattern p = Pattern.compile("\\d{1,10}");
		Matcher matcher = p.matcher(text);
		return matcher.matches();
	}

	private void showErrMsg(JTextField tf, String infoMsg) {
		if (err_info == null) {
			err_info = new JLabel();
		}
		err_info.setVisible(true);
		err_info.setText(tf.getText() + infoMsg);
	}

	@Override
	public void focusGained(FocusEvent e) {

	}

	@Override
	public void focusLost(FocusEvent e) {

	}

	public static boolean isNullOrEmpty(String str) {
		if (str == null || str.trim().equals(""))
			return true;
		else
			return false;
	}

	public void setDefaultValue(JTextField tf, String value) {
		if (isNullOrEmpty(tf.getText())) {
			tf.setText(value);
		}
	}
}
